package com.yeziji.security.common;

import cn.hutool.extra.spring.SpringUtil;
import com.yeziji.security.common.reader.BaseReader;
import com.yeziji.security.utils.JwtUtils;
import com.yeziji.service.cache.RedisService;
import com.yeziji.utils.LockUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 加密令牌上下文
 *
 * @author hwy
 * @since 2023/11/12 19:41
 **/
@Component
public class SecurityTokenContext {
    @Resource
    private BaseReader baseReader;
    private static RedisService redisService;
    private static boolean useCache = false;
    /**
     * 记录 token 的加密令牌信息
     */
    private static final Map<String, SecurityToken> TOKEN_MAP = new ConcurrentHashMap<>();
    private static final String SECURITY_CACHE_KEY = "yzj:security:";

    @PostConstruct
    @SuppressWarnings("all")
    public void init() {
        if (this.baseReader != null) {
            if ((useCache = this.baseReader.isOpenRedisCache())) {
                LockUtils.newInstance(false).execute(() -> {
                    if (redisService == null) {
                        redisService = SpringUtil.getBean(RedisService.class);
                    }
                });
            }
        }
    }

    /**
     * 获取加密令牌对象信息
     *
     * @param token 令牌
     * @return {@link SecurityToken} 加密令牌对象
     */
    public static SecurityToken get(String token) {
        String cacheKey = getCacheKey(token);
        SecurityToken securityToken;
        if (isUseCache()) {
            securityToken = redisService.get(cacheKey);
        } else {
            securityToken = TOKEN_MAP.get(cacheKey);
        }
        return securityToken;
    }

    /**
     * 赋值加密令牌对象信息
     *
     * @param token         令牌
     * @param securityToken 加密令牌对象
     */
    public static void put(String token, SecurityToken securityToken) {
        String cacheKey = getCacheKey(token);
        if (isUseCache()) {
            long remainingTime = JwtUtils.getRemainingTime(securityToken.getOriginalToken());
            redisService.set(cacheKey, securityToken, remainingTime, TimeUnit.MILLISECONDS);
        } else {
            TOKEN_MAP.put(cacheKey, securityToken);
        }
    }

    /**
     * 删除指定的 token
     *
     * @param token 令牌
     */
    public static void remove(String token) {
        String cacheKey = getCacheKey(token);
        if (isUseCache()) {
            redisService.remove(cacheKey);
        } else {
            TOKEN_MAP.remove(cacheKey);
        }
    }

    /**
     * 遗弃指定的 token
     *
     * @param token 令牌
     */
    public static void deprecated(String token) {
        SecurityToken securityToken = get(token);
        if (securityToken != null) {
            securityToken.setDeprecated(true);
        }
        // 更新缓存
        String cacheKey = getCacheKey(token);
        if (isUseCache()) {
            long remainingTime = JwtUtils.getRemainingTime(token);
            redisService.set(cacheKey, securityToken, remainingTime, TimeUnit.MILLISECONDS);
        } else {
            TOKEN_MAP.put(cacheKey, securityToken);
        }
    }

    /**
     * 是否令牌被遗弃
     *
     * @param token 令牌
     * @return {@link Boolean}
     */
    public static boolean isDeprecated(String token) {
        String cacheKey = getCacheKey(token);
        SecurityToken securityToken;
        if (isUseCache()) {
            securityToken = redisService.get(cacheKey);
        } else {
            securityToken = TOKEN_MAP.get(cacheKey);
        }
        return securityToken != null && securityToken.isDeprecated();
    }

    /**
     * 更新加密令牌对象信息
     *
     * @param oldToken      旧的 token
     * @param securityToken 新的 token
     */
    public static void update(String oldToken, SecurityToken securityToken) {
        remove(oldToken);
        put(securityToken.getOriginalToken(), securityToken);
    }

    /**
     * 获取当前 securityContextHolder 的 authorities role name
     */
    public static Set<String> getContextAuthorities() {
        return SecurityContextHolder.getContext()
                .getAuthentication()
                .getAuthorities()
                .stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toSet());
    }

    /**
     * 是否使用 cache 保存上下文会话
     *
     * @return {@link Boolean}
     */
    private static boolean isUseCache() {
        return useCache && redisService != null;
    }

    /**
     * 构建 cache key
     *
     * @param suffix 后缀
     * @return {@link String}
     */
    private static String getCacheKey(String suffix) {
        return SECURITY_CACHE_KEY + suffix;
    }
}
